﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

using CXJ.Interface;

namespace CXJ.Libiary
{
    public class DBManager
    {
        public static string _DBTYPE = "CXJ.DLL";
        public static string _DBTYPEName = "CXJ.DLL.SqlDBOperator";
        public static string _DBOPERATENAME = "CXJ.DLL.DataOperater";
        private static string _CONNECTIONSTRING = "Server=#IP#,#PORT#;DataBase=#DATABASE#;Uid=#USERID#;Pwd=#PASSWORD#";

        private static IDBOperator _Instance;

        public static IDBOperator Instance
        {
            get
            {
                if (_Instance == null)
                {
                    ReadConfig();
                    _Instance = CreateDBOperate();
                }
                return _Instance;
            }
        }

        private static IDBOperator CreateDBOperate()
        {
            IDBOperator objvlaue = null;
            try
            {
                Assembly pAssembly = Assembly.Load(_DBTYPE);
                objvlaue = (IDBOperator)pAssembly.CreateInstance(_DBTYPEName);
                objvlaue.ConnectString = _CONNECTIONSTRING;
            }
            catch { }
            return objvlaue;
        }
        private static void ReadConfig()
        {
            IniFile pIniFile = new IniFile("config.ini");
            string pIP = pIniFile.ReadString("Server", "Address", ".");
            string pPort = pIniFile.ReadString("Server", "Port", "1433");
            string pDataBase = pIniFile.ReadString("Server", "DataBase", "");
            string pUserName = pIniFile.ReadString("Server", "UserName", "sa");
            string pPassword = pIniFile.ReadString("Server", "Password", "");
            _CONNECTIONSTRING = _CONNECTIONSTRING.Replace("#IP#", pIP);
            _CONNECTIONSTRING = _CONNECTIONSTRING.Replace("#PORT#", pPort);
            _CONNECTIONSTRING = _CONNECTIONSTRING.Replace("#DATABASE#", pDataBase);
            _CONNECTIONSTRING = _CONNECTIONSTRING.Replace("#USERID#", pUserName);
            _CONNECTIONSTRING = _CONNECTIONSTRING.Replace("#PASSWORD#", pPassword);

            _DBTYPE = pIniFile.ReadString("Provider", "DBType", _DBTYPE);
            _DBTYPEName = pIniFile.ReadString("Provider", "DBTypeName", _DBTYPEName);
            _DBOPERATENAME = pIniFile.ReadString("Provider", "DBOperaterName", _DBOPERATENAME);
        }
    }
}
